package com.magic.gre.base.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.magic.gre.R;
import com.magic.gre.base.dialog.BaseDialog;
import com.magic.gre.entity.base.BaseWheelIm;
import com.magic.gre.helper.Apphelper;
import com.magic.gre.ui.activity.LoginActivity;
import com.magic.gre.ui.dialog.LoginHintDialog;
import com.magic.gre.ui.dialog.MultipleBottomDialog;
import com.noname.lib_base_java.entity.MsgEvent;
import com.noname.lib_base_java.net.RxBus;
import com.noname.lib_base_java.util.ActivityManager;
import com.noname.lib_base_java.util.ToastUtil;

import java.util.List;

import butterknife.ButterKnife;
import io.reactivex.functions.Consumer;

/**
 * Author: Lmoumou
 * Date: 2018-12-05 16:43
 * 文件名: BaseActivity
 * 描述:
 */
public abstract class BaseActivity extends AppCompatActivity implements LoginHintDialog.OnLoginHintDialogListener,
        BaseDialog.DismissListanner {
    private LoginHintDialog loginDialog;
    public LoginHintDialog getLoginDialog() {
        if (loginDialog == null) {
            loginDialog = new LoginHintDialog();
        }
        return loginDialog;
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityManager.getInstance().addActivity(this);
        initStatusBar();
        int layoutId = getLayoutId();
        if (layoutId > 0) {
            setContentView(layoutId);
        }
        ButterKnife.bind(this);

        Toolbar toolbar = (Toolbar) findViewById(R.id.titleTb);
        initToolbar(toolbar, 0, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        initView(savedInstanceState);
    }

    protected void initToolbar(Toolbar mToolbar, int iconResId, View.OnClickListener listener) {
        if (mToolbar != null) {
            mToolbar.setTitle("");
            this.setSupportActionBar(mToolbar);
            ActionBar actionBar = this.getSupportActionBar();
            if (actionBar != null) {
                actionBar.setHomeButtonEnabled(true);
                actionBar.setDisplayHomeAsUpEnabled(true);
                if (iconResId > 0) {
                    actionBar.setHomeAsUpIndicator(iconResId);
                } else {
                    actionBar.setHomeAsUpIndicator(R.mipmap.ic_back);
                }
            }
            if (listener != null) {
                mToolbar.setNavigationOnClickListener(listener);
            }

        }
    }


    private void initStatusBar() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (isImmerse()) {
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                        | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//API 23以上
                setTextDark();
                if (isImmerse()) {//沉浸->状态栏为透明
                    getWindow().setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
                } else {//非沉浸->状态栏颜色动态设置
                    getWindow().setStatusBarColor(statusColorBy23());
                }
            } else {
                if (isImmerse()) {//沉浸->状态栏为透明
                    getWindow().setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
                } else {//非沉浸->状态栏颜色动态设置
                    getWindow().setStatusBarColor(statusColor());
                }
            }
            /*} else {
                if (isImmerse()) {
                    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                }
                //状态栏管理实例
                SystemBarTintManager tintManager = new SystemBarTintManager(this);
                //激活状态栏设置
                tintManager.setStatusBarTintEnabled(true);
                //设置状态栏颜色
                tintManager.setStatusBarTintResource(colorId);
            }*/
        }
    }


    /**
     * 设置6.0以上状态栏深色文字
     */
    private void setTextDark() {
        Window window = this.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);   //清除4.4设置的透明样式
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        int flag = window.getDecorView().getSystemUiVisibility() | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        window.getDecorView().setSystemUiVisibility(flag);
    }

    /**
     * 显示软键盘
     */
    public void showSoftInput(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInput(view, 0);
        }
    }

    /**
     * 关闭软键盘
     */
    public void closeKeyBord(View view) {
        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(view.getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public void closeKeyBord() {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if(imm.isActive()&&getCurrentFocus()!=null){
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken()!=null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 订阅RxBus
     */
    @SuppressLint("CheckResult")
    protected void registerRxBus() {
        RxBus.getInstance().toObservable(this, MsgEvent.class)
                .subscribe(new Consumer<MsgEvent>() {
                    @Override
                    public void accept(MsgEvent msgEvent) throws Exception {
                        handlerMsg(msgEvent);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                });

    }

    protected void handlerMsg(MsgEvent msgEvent) {

    }

    /**
     * 检测是否登陆
     *
     * @return
     */
    public boolean isValidAccount(){
        if (TextUtils.isEmpty(Apphelper.getToken())){

            if (!getLoginDialog().isResumed()) {
               showLoglinDialog();
            }

            return false;
        }
        return true;
    }

    public void showLoglinDialog() {
        getLoginDialog().setDismissListanner(this);
        getLoginDialog().showThis(getSupportFragmentManager(), LoginHintDialog.class.getSimpleName(),this);
    }

    @Override
    public void onDialogMiss() {
       this.finish();
    }

    @Override
    public void onCancel() {

    }

    @Override
    public void onLogin() {
        LoginActivity.startThis(this);
    }



    protected void showDialog(MultipleBottomDialog mixBottomDialog, int id, TextView textView, List<BaseWheelIm> beens) {
        try {
            if (beens == null || beens.isEmpty()) {
                ToastUtil.getInstance().showNormal(this, "暂无数据");
            } else {
                mixBottomDialog.showThis(getSupportFragmentManager(), String.valueOf(id), beens, (Integer) textView.getTag());
            }
        } catch (Exception e) {
            e.printStackTrace();
            mixBottomDialog.showThis(getSupportFragmentManager(), String.valueOf(id), beens, 0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManager.getInstance().removeActivity(this);
    }


    /**
     * 布局文件Id
     *
     * @return
     */

    protected abstract int getLayoutId();

    /**
     * 是否沉浸
     */
    protected abstract boolean isImmerse();

    /**
     * 设置状态栏颜色(6.0以下)
     *
     * @return
     */

    protected abstract int statusColor();

    /**
     * 设置状态栏颜色(6.0以上)
     *
     * @return
     */

    protected abstract int statusColorBy23();

    /**
     * 初始化
     */
    protected abstract void initView(@Nullable Bundle savedInstanceState);

}
